import Vue from 'vue'
// import Router from 'vue-router'
import LoginView from '@/views/login/index'
/*element-message*/
import { Message  } from 'element-ui';

Vue.use(VueRouter)

/*定义路由 并输出*/
const router = new VueRouter({
    // mode: 'history',
    scrollBehavior(to,from,savedPosition){
        /*有缓存的页面，重新回到原位置*/
        if(document.querySelector('.el-main')){
            if (to.meta.keepAlive) {
              document.querySelector('.el-main').scrollTop =to.meta.savedPosition
            }
            else{
              /*content-filed，el-main，方便页面之间跳转时，每个页面都是从最顶的位置开始显示*/
              document.querySelector('.el-main').scrollTop =0
            }
        }
    },
    routes: [
      {
          path: '/login',
          name: "login",
          component: LoginView,
          meta: { requiresAuth: false }
      },
      // {
      //   path: '/',
      //   name: "index",
      //   component: index,
      //   meta: { requiresAuth: true },
      //   children:[
      //   ...generateChildRouters()
      //   ]
      // }
    ],
});
/*生成首页路由-动态生成则无需在这里生成-未有动态路由时在这里生成;页面刷新时，需要重新生成路由*/
generateIndexRouter();

/*路由拦截器设置-before*/
router.beforeEach((to, from, next) => {
     /*有缓存的页面，重新回到原位置*/
    if(from.meta.keepAlive == true){
        from.meta.savedPosition = document.querySelector('.el-main').scrollTop
    }

    /*修改后提交到列表页 设置不缓存，其余页面返回列表页设置缓存*/
    if(from.meta.modifyCacheRoute){
        router.app.$store.commit('setcacheRoute', []);
    }
    else{
        router.app.$store.commit('setcacheRoute',router.app.Global.cacheRouteArr );
    }
    let token = sessionStorage.getItem('token')
  	//1.登录权限判断
    if(to.meta.requiresAuth) {
        //验证token，存在才跳转
        if(token) {
            next()
        } 
        else {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }
    } 
    else{
        if(to.path === '/' ) {
            /*后退到login时拦截*/
            if(token){
                next({path:'/homework'})
            }
            //根目录（刚进入页面时）
            else{
                next({path: '/login'})
            }
        }
        else{
          // alert(to.path)
            next()
        }
    }
    /*2.非登陆条件下输入某个地址 需要先跳到登录页再跳转到相应页面*/
    if(to.matched.length == 0 ){
        next({path: '/login',query: { redirect: to.fullPath }})
    }
});

router.afterEach((to, from) => {
    // 设置面包屑
    let breadCrumbItems = []
    let homePageCrumb = {
        title: '首页',
        to: '/'
    }
    /* not index add*/
    if(to.meta.title != '首页'){
        breadCrumbItems.push(homePageCrumb)
    }
    
    if(to.meta.title) {
        /*title  split =>arr*/
        let fullPathSplit = to.meta.title.split('/')
        
        let sec_path = '/'+to.path.split('/')[1]
        //二级目录 需要link
        if(sec_path == '/company'  || sec_path == '/examine' ){
            fullPathSplit.forEach(( item, index ) => {
                let routerBreadCrumb = {
                    title: item,
                    to: (index == 0 ? sec_path : '' )
                }
                breadCrumbItems.push(routerBreadCrumb)
            });
        }
        //二级目录 无link
        else{
            fullPathSplit.forEach(( item, index ) => {
                let routerBreadCrumb = {
                    title: item,
                    to: (index == 0 ? '' : ( index == fullPathSplit.length - 1 ? to.path : sec_path) ) 
                }
                breadCrumbItems.push(routerBreadCrumb)
            });
        }
    }
    // 更新到state
     router.app.$store.commit('setbreadcrumbItems', breadCrumbItems);
})

// 生成首页路由
function generateIndexRouter() {
  /*sessionStorage exit first*/
  if (!window.sessionStorage.getItem('routers')) {
    return
  }
  /*index router*/
  let indexRouter = {
    path: '/',
    name: "index",
    component:()=>import('@/views/home/index.vue'),
    children: [
      ...generateChildRouters()
    ]
  }
  // return indexRouter
  router.addRoutes([indexRouter])
}

// 生成嵌套路由（子路由）
function generateChildRouters() {
  // if (sessionStorage.length == 0) {
  //   return {}
  // }
  let routers = JSON.parse(sessionStorage.getItem('routers'))
  let childRouters = []
  
  for(let router of routers) {
      try {
        if(router.isRouter == '1'  ){  
          let routerProps = JSON.parse(router.routerCode)
          if(routerProps){
            // let index_props = 'views/homework/index'  //将路径拆解成 '@/' + ... 这样才能正确解析 
            let childRouter = {
                path: routerProps.path,
                name: routerProps.name,
                // component:resolve => require(['@/' + routerProps.component], resolve), //Vue的异步组件技术
                // component:r => require.ensure([], () => r(require('@/' + routerProps.component)), 'demo'),//webpack提供的require.ensure(),这样可以实现按需加载，并且你可以将多个相同类的组件打包成一个文件
                component:()=>import('@/' + routerProps.component),//es提案的import（） 
                meta: routerProps.meta
            }
            
            childRouters.push(childRouter)
          }
        }
      }catch (ex) {
        console.warn(ex.message)
      }
  }
  return childRouters
}
 

// 路由报错
router.onError(error => {
    // 已有路由未配置页面文件的情况下
    /* error  tip*/
    Message({type:'error',message:'页面暂时不能访问，请联系管理员或稍后再试'})
})
export default router;

